package org.TCC_NOVO.client.visual;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Grid;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import java.util.List;

import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.modelo.Papel;
import org.TCC_NOVO.client.modelo.Usuario;

public class UsuariosForm extends Window {

    private UsuariosPanel usuaPanel;
    public int IDForm = 0;
    private final GWTServiceAsync controller;
    private UsuariosForm Self;

    private FormPanel formPanel;
    private TextField txtNick;
    private TextField txtSenha;
    private TextField txtSenhaConf;
    private TextField txtNome;
    private TextField txtEmail;
    private ComboBox cb;
    private boolean edit;
    private Record record;
    private Panel panelPrin;

    public UsuariosForm(UsuariosPanel UsuaPanel, GWTServiceAsync controller) {
        this.usuaPanel = UsuaPanel;
        this.controller = controller;
        this.Self = this;
        this.init();
        this.setModal(true);
    }

    private void init(){
        panelPrin = getPanelCentral();
        this.add(panelPrin);
        this.setTitle("Cadastro de Usuários");
    }

    private Usuario getUsuarioForm(){
        Usuario u = new Usuario();
        if (edit)
           u.setId(IDForm);
        u.setNome(txtNome.getText());
        u.setNick(txtNick.getText());
        u.setSenha(txtSenha.getText());
        u.setEmail(txtEmail.getText());
        u.setPapel(new Papel(Integer.valueOf(cb.getValue()), "")); // o que importa é ficar com o id

        return u;
    }

    private Panel getPanelCentral(){
        Panel panel = new Panel();
        panel.setBorder(false);
        panel.setPaddings(1);

        formPanel = new FormPanel();
        formPanel.setFrame(true);
        formPanel.setWidth(350);
        formPanel.setLabelWidth(75);

        txtNick = new TextField("Nick", "Nick", 230);
        //txtNick.setAllowBlank(false);
        txtNick.setBlankText("Este campo é obrigatório");
        formPanel.add(txtNick);

        txtSenha = new TextField("Senha", "Senha", 230);
        txtSenha.setAllowBlank(true);
        txtSenha.setInputType("password");
        formPanel.add(txtSenha);

        txtSenhaConf = new TextField("Conf. Senha", "SenhaConfig", 230);
        txtSenhaConf.setAllowBlank(true);
        txtSenhaConf.setInputType("password");
        formPanel.add(txtSenhaConf);

        txtNome = new TextField("Nome", "Nome", 230);
        txtNome.setAllowBlank(true);
        formPanel.add(txtNome);

        txtEmail = new TextField("Email", "Email", 230);
        txtEmail.setAllowBlank(true);
        formPanel.add(txtEmail);

        cb = new ComboBox();
        cb.setForceSelection(true);
        cb.setMinChars(1);
        cb.setFieldLabel("Papel");
        cb.setDisplayField("papel");
        cb.setValueField("ID");
        cb.setMode(ComboBox.LOCAL);
        cb.setTriggerAction(ComboBox.ALL);
        cb.setEmptyText("Selecione o Papel");
        cb.setLoadingText("Searching...");
        cb.setTypeAhead(true);
        cb.setSelectOnFocus(true);
        cb.setWidth(txtNome.getWidth());
        cb.setHideTrigger(false);
        cb.setName("Idf_papel");
        formPanel.add(cb);

        controller.retornarDadosPapeis(new AsyncCallback<List<Papel>>() {

            @Override
            public void onFailure(Throwable caught) {
                MessageBox.alert("Erro ", caught.getMessage());
            }

            @Override
            public void onSuccess(List<Papel> result) {

                String[][] papeis = new String[result.size()][2];

                for (int x=0; x < result.size(); x++) {
                    papeis[x][0] = result.get(x).getId()+"";
                    papeis[x][1] = result.get(x).getNome();
                }

                final Store store = new  SimpleStore(0, new String[]{"ID", "papel"}, papeis);
                store.load();
                cb.setStore(store);

            }

        });


        final AsyncCallback callbackUsuario = new AsyncCallback() {
            public void onSuccess(Object result) {
                //MessageBox.alert("Registro Gravado com Sucesso!");
            }
            public void onFailure(Throwable caught) {
               MessageBox.alert("Erro ", caught.getMessage()); }
        };

        final Button save = new Button();
        save.setText(" Salvar");
        save.setIcon("Images/salvar.png");
        save.setTooltip("Salvar");
        save.addListener(new ButtonListenerAdapter(){
            @Override
            public void onClick(Button button, EventObject e){
                    if (txtSenha.getText().equals(txtSenhaConf.getText())){
                        if (!txtSenha.getText().equals("")){
                            Usuario usua = getUsuarioForm();
                            String sSql;
                            if (edit){
/*
                                sSql = "Update Usuario set Nick = '"+usua.getNick()+"' where ID = "+usua.getId();
                                controller.EditarRegistro(sSql, callbackUsuario);
                                sSql = "Update Usuario set Nome = '"+usua.getNome()+"' where ID = "+usua.getId();
                                controller.EditarRegistro(sSql, callbackUsuario);
                                sSql = "Update Usuario set Senha = '"+usua.getSenha()+"' where ID = "+usua.getId();
                                controller.EditarRegistro(sSql, callbackUsuario);
                                sSql = "Update Usuario set Email = '"+usua.getEmail()+"' where ID = "+usua.getId();
                                controller.EditarRegistro(sSql, callbackUsuario);
                                sSql = "Update Usuario set IDF_Papel = '"+cb.getValue()+"' where ID = "+usua.getId();
                                controller.EditarRegistro(sSql, callbackUsuario);*/
                                controller.salvarUsuario(usua, callbackUsuario);
                                //alteração do registro no cliente (Grid)...
                                updateUsuario(cb.getRawValue(), usua.getId());
                                Self.hide();
                            }else{
                                if (existeUsuario(usua.getNick())){
                                    MessageBox.alert("Erro ", "Já existe um usuário com o Nick "+usua.getNick());
                                }else{
                                    //Inclusao do registro no servidor (Banco de Dados)...
                                    controller.salvarUsuario(usua, callbackUsuario);

                                    //Inclusao do registro no cliente (Grid)...                                    
                                    salvarUsuario(usua);
                                    //UsuaPanel.CarregarGrid();
                                    Self.hide();
                                }
                            }
                        }else{
                            MessageBox.alert("Senha não pode ser vazia!");
                        }
                    }else{
                        MessageBox.alert("Senhas não são iguais!");
                    }
            }            
        });
        formPanel.addButton(save);

        final Button cancel = new Button();
        cancel.setText(" Cancelar");
        cancel.setIcon("Images/cancelar.png");
        cancel.setTooltip("Cancelar");
        cancel.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                MessageBox.confirm("Deseja realmente sair?", "Todos os dados não submetidos serão perdidos", new MessageBox.ConfirmCallback() {
                    @Override
                    public void execute(String btnID) {
                        if (btnID.equals("yes")){
                            hide();
                        }
                        throw new UnsupportedOperationException("Not supported yet.");
                    }
                });
            }
        });
        formPanel.addButton(cancel);
        panel.add(formPanel);
        return panel;
    }

    private boolean existeUsuario(String nick){
        boolean b = false;
        int count = 0;
        this.usuaPanel.getStore().filter("Nick", nick);
        count = this.usuaPanel.getStore().getCount();
        if (count > 0){
            b = true;
        }
        this.usuaPanel.getStore().clearFilter();
        return b;
    }

    private void salvarUsuario(Usuario usua){
        this.usuaPanel.addRecord(usua);        
    }

    private void updateUsuario(String papel, long ID){
        //record.set("Papel", papel);
        //record.commit();
        //this.UsuaPanel.store.getById(Integer.toString(ID)).beginEdit();
        this.usuaPanel.getStore().getById(Long.toString(ID)).set("Papel", papel);
        formPanel.getForm().updateRecord(record);
    }

    public void show(boolean edit){
        this.edit = edit;
        if (edit){
            initEdit();
        }else{
            initNew();
        }
        show();
    }

    private void initEdit(){
        txtNick.focus();
        //txtNick.setDisabled(true);
    }

    private void initNew(){
        txtEmail.setValue("");
        txtNome.setValue("");
        txtSenha.setValue("");
        txtSenhaConf.setValue("");
        txtNick.setDisabled(false);
        txtNick.setValue("");
        cb.setValue("");
        txtNick.focus();
    }

    public void loadRecord(Record record){
        this.record = record;
        formPanel.getForm().loadRecord(record);
    }

}
